<!-- ALL-数据可视化-可视化基础树形组件配置 -->
<template>
  <div>
    <div class="equip-wrap-common">
      <!--左侧树形结构 -->
      <div class="equip-tree-wrap">
        <div class="equip-tree-content">
          <px-input v-model="filterTextLeft" style="margin-right: 6px" placeholder="请输入关键字搜索" />
          <px-tooltip content="全部收折" placement="top">
            <px-button v-show="isTreeOpen" link type="primary" icon="ChevronUpRectangle" @click="openOrCloseTreeLeft('close')" />
          </px-tooltip>
          <px-tooltip content="全部展开" placement="top">
            <px-button v-show="!isTreeOpen" link type="primary" icon="ChevronDownRectangle" @click="openOrCloseTreeLeft('open')" />
          </px-tooltip>
          <px-tooltip content="清除选中" placement="top">
            <px-button style="margin-left: 4px" link type="primary" icon="RefreshLeft" @click="resetCheckLeft" />
          </px-tooltip>
        </div>
        <px-scrollbar class="equip-scroll">
          <px-tree
            ref="treeRefLeft"
            :default-checked-keys="defaultCheckedKeys"
            :data="treeDataLeft"
            :props="{ children: 'children', label: 'name' }"
            default-expand-all
            node-key="id"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            highlight-current
            :expanded-keys="expandedKeys"
            @node-click="nodeClick"
          >
            <template #default="{ node }">
              <span style="display: flex; align-items: center; height: 100%" class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </px-tree>
        </px-scrollbar>
      </div>
      <!-- 中间树结构 -->
      <div class="equip-tree-wrap">
        <div class="equip-tree-content">
          <px-input v-model="filterTextRight" style="margin-right: 6px" placeholder="请输入关键字搜索" />
          <px-tooltip content="全部收折" placement="top">
            <px-button v-show="isTreeOpen" link type="primary" icon="ChevronUpRectangle" @click="openOrCloseTreeRight('close')" />
          </px-tooltip>
          <px-tooltip content="全部展开" placement="top">
            <px-button v-show="!isTreeOpen" link type="primary" icon="ChevronDownRectangle" @click="openOrCloseTreeRight('open')" />
          </px-tooltip>
          <px-tooltip content="清除选中" placement="top">
            <px-button style="margin-left: 4px" link type="primary" icon="RefreshLeft" @click="resetCheckRight" />
          </px-tooltip>
          <px-button style="margin-right: 4px" type="primary" :disabled="!twinId" @click="AddTree(0)">新增组件</px-button>
        </div>
        <px-scrollbar class="equip-scroll">
          <px-tree
            ref="treeRefRight"
            :default-checked-keys="defaultCheckedKeys"
            :data="treeDataRight"
            :props="{ children: 'children', label: 'name' }"
            default-expand-all
            node-key="id"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            highlight-current
            :expanded-keys="expandedKeys"
            @node-click="nodeClickPlus"
          >
            <template #default="{ node, data }">
              <span style="display: flex; align-items: center; height: 100%" class="custom-tree-node">
                <span>{{ `${node.label}--${data.className ? data.className : ""}` }}</span>
                <span style="position: relative; display: inline-block">
                  <px-dropdown trigger="click">
                    <px-button link type="primary" icon="More" @click.stop="showDropdown(data)" />
                    <template #dropdown>
                      <px-dropdown-menu>
                        <px-dropdown-item v-if="!parentNo" @click="AddTree(data)">
                          <px-icon> <Plus /> </px-icon><span>新增子组件</span></px-dropdown-item
                        >
                        <px-dropdown-item @click="EditTree(data)"
                          ><px-icon> <EditPen /> </px-icon><span>编辑</span></px-dropdown-item
                        >
                        <px-dropdown-item @click="DeleteTree(data)"
                          ><px-icon> <Delete /> </px-icon><span>删除</span></px-dropdown-item
                        >
                      </px-dropdown-menu>
                    </template>
                  </px-dropdown>
                </span>
              </span>
            </template>
          </px-tree>
        </px-scrollbar>
      </div>
      <!-- 右侧整体功能 -->
      <div class="equip-table-wrap">
        <!-- 按钮功能 -->
        <div class="equip-table-btn">
          <px-button style="margin-right: 8px" type="primary" :disabled="!componentNo" @click="addTableType">新增</px-button>
          <px-button style="margin-right: 8px" type="primary" :disabled="!componentNo" @click="addTableSensorType">新增传感器</px-button>

          <BatchUpload url="/ifp/digitaltwins/api/v1/visualComponent/importData" permission="" title="导入" />
          <px-button type="danger" plain @click="batchDelete">批量删除</px-button>
        </div>
        <!-- 表格功能 -->
        <px-table
          :data="tableData"
          class="equip-table"
          size="small"
          height="calc(100vh - 311px)"
          style="width: 75%"
          border
          @selection-change="selectionChange"
        >
          <px-table-column type="selection" min-width="40" align="center" fixed="left" />
          <px-table-column type="index" label="序号" min-width="60" align="center" fixed="left" />
          <px-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template #default="scope">
              <span>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" min-width="120" align="center">
            <template #default="scope">
              <px-tooltip content="编辑" placement="top">
                <px-button link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="复制" placement="top">
                <px-button link type="primary" icon="CopyDocument" @click="handleCopy(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 中间添加树类型页面 -->
    <AddTreeDetail
      :rightData="rightData"
      :parentNo="parentNo"
      :twinId="twinId"
      :TreedialogVisible="TreedialogVisible"
      :dialogType="dialogType"
      :dialogRow="dialogRow"
      :treeDataRight="treeDataRight"
      @queryTable="queryTable"
      @queryTreeRight="queryTreeRight"
      @closeDialog="closeDialog"
    />
    <!-- 右侧设备类型新增/编辑页面 -->
    <AddTableDetail
      :rowData="rowData"
      :componentNo="componentNo"
      :TabledialogVisible="TabledialogVisible"
      :rightData="rightData"
      :parentNo="parentNo"
      :twinId="twinId"
      :tableType="tableType"
      :dialogRow="dialogRow"
      @queryTable="queryTable"
      @queryTreeRight="queryTreeRight"
      @closeDialog="closeDialog"
    />
    <AddTableSensorDetail
      v-model:open-dialog="TabledialogSensorVisible"
      :componentNo="componentNo"
      @queryTable="queryTable"
      @queryTreeRight="queryTreeRight"
      @closeDialog="closeSensorDialog"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_SPAREPARTS_LEDGER"
});
import { onMounted, reactive, toRefs, watch, getCurrentInstance, ref } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import AddTreeDetail from "./components/AddTreeDetail.vue";
import AddTableDetail from "./components/AddTableDetail.vue";
import AddTableSensorDetail from "./components/AddTableSensorDetail.vue";
import { queryFacPositionTree, listByTwinId, queryPageList, delByComponentNo, delByIds } from "@/api/visual/module";
import BatchUpload from "@/components/Upload/BatchUpload.vue";
const state = reactive<any>({
  parentCode: "",
  filterTextLeft: "",
  filterTextRight: "",
  treeRefLeft: null,
  treeRefRight: null,
  treeDataLeft: [],
  treeDataRight: [],
  expandedKeys: [],
  isTreeOpen: true,
  TreedialogVisible: false,
  TabledialogVisible: false,
  TableSensorType: "",
  TabledialogSensorVisible: false,
  dialogRow: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    componentNo: ""
  },
  componentNo: "",
  formValue: {
    eqpId: "",
    eqpName: "",
    facCode: "",
    facName: "",
    typeCode: "",
    positionCode: ""
  },
  treeDataPlus: "",
  tableColumns: [
    { prop: "title", label: "属性名称", minWidth: "150", showOverflowTooltip: true, fixed: "left" },
    { prop: "specCode", label: "位号", minWidth: "180", showOverflowTooltip: true, fixed: "left" },
    { prop: "tagNum", label: "自定义位号", minWidth: "120", showOverflowTooltip: true },
    { prop: "componentNo", label: "组件编码", minWidth: "150", showOverflowTooltip: true },
    { prop: "unit", label: "单位", minWidth: "120", showOverflowTooltip: true },
    { prop: "value", label: "值", minWidth: "80", showOverflowTooltip: true },
    { prop: "valueType", label: "值类型", minWidth: "80", showOverflowTooltip: true },
    { prop: "valueEnum", label: "值枚举", minWidth: "120", showOverflowTooltip: true },
    { prop: "createTime", label: "创建时间", minWidth: "150", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  selectIds: [],
  downloadParams: {
    ids: [],
    systemCode: "",
    facCode: "",
    value: "",
    positionCode: "",
    eqpStatus: ""
  },
  rowData: {},
  dialogType: "add",
  tableType: "add",
  defaultCheckedKeys: [],
  nodeClickLeft: "",
  twinId: "",
  parentNo: "",
  rightData: {}
});
const {
  rowData,
  rightData,
  parentNo,
  twinId,
  componentNo,
  nodeClickLeft,
  filterTextLeft,
  filterTextRight,
  parentCode,
  treeRefLeft,
  treeRefRight,
  treeDataLeft,
  treeDataRight,
  expandedKeys,
  isTreeOpen,
  TreedialogVisible,
  TabledialogVisible,
  TableSensorType,
  TabledialogSensorVisible,
  dialogRow,
  queryParams,
  tableColumns,
  tableData,
  total,
  selectIds,
  dialogType,
  tableType,
  defaultCheckedKeys
} = toRefs(state);

// 监视过滤树的值
watch(filterTextLeft, val => {
  treeRefLeft.value!.filter(val);
});
watch(filterTextRight, val => {
  treeRefRight.value!.filter(val);
});
// 进入页面时触发
onMounted(() => {
  queryTree();
});
/** 左侧-树形区 **/
// 进入页面加载左侧树
const queryTree = async () => {
  const data: any = await queryFacPositionTree({
    facCode: localStorage.getItem("facCode"),
    name: ""
  });
  console.log(data, "queryTree");
  treeDataLeft.value = data;
};
// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
///树形下拉
const showDropdown = data => {
  parentCode.value = data.parentCode;
  parentNo.value = data.parentNo;
  rightData.value = data;
};

// 左侧树添加清除选中按钮
const resetCheckLeft = () => {
  filterTextLeft.value = "";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
  queryParams.value = {
    pageNum: 1,
    pageSize: 20
  };
};
// 右侧树添加清除选中按钮
const resetCheckRight = () => {
  filterTextRight.value = "";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
  queryParams.value = {
    pageNum: 1,
    pageSize: 20
  };
};
// 点击左侧树节点
const nodeClick = (data, node) => {
  nodeClickLeft.value = data.code;
  twinId.value = data.code;
  queryTreeRight();
};

// 点击中间树节点
const nodeClickPlus = (data, node) => {
  queryParams.value.componentNo = data.componentNo;
  componentNo.value = data.componentNo;
  queryTable();
};
// 中间树结构
const queryTreeRight = async () => {
  const data: any = await listByTwinId(nodeClickLeft.value);
  treeDataRight.value = data;
};

// 打开或者关闭左侧树
const openOrCloseTreeLeft = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRefLeft.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRefLeft.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};
// 打开或者关闭左侧树
const openOrCloseTreeRight = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRefRight.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRefRight.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};

// 新增树形组件
const AddTree = data => {
  dialogType.value = "add";
  TreedialogVisible.value = true;
  dialogRow.value = data;
};
// 编辑树形组件显示弹窗
const EditTree = data => {
  dialogType.value = "edit";
  dialogRow.value = data;
  TreedialogVisible.value = true;
};

// 删除树形组件
const DeleteTree = async (data: any) => {
  PxMessageBox.confirm(`确定要删除当前设备类型“${data.name}”吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delByComponentNo(data.componentNo);
      PxMessage.success("删除成功");
      queryTreeRight();
    })
    .catch(() => {});
};

// 查询备件台账列表
const queryTable = async () => {
  const data: any = await queryPageList({ ...queryParams.value });
  tableData.value = data?.data;
  total.value = data?.total;
};

// 新增设备类型台账按钮
const addTableType = () => {
  tableType.value = "add";
  TabledialogVisible.value = true;
};

// 表格多选框选中-批量导出、批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
  console.log(selectIds.value);
};
// 批量删除按钮
const batchDelete = async () => {
  if (selectIds.value.length == 0) {
    PxMessage.warning("请选择属性后操作");
    return;
  }
  PxMessageBox.confirm(`要删除当前已选的 ${selectIds.value.length} 个设备吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delByIds({
        ids: selectIds.value
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};

// 编辑单条属性
const handleEdit = (row: any) => {
  tableType.value = "edit";
  TabledialogVisible.value = true;
  dialogRow.value = row;
};
// 复制单条数据
const handleCopy = (row: any) => {
  tableType.value = "copy";
  TabledialogVisible.value = true;
  dialogRow.value = row;
};
// 删除单条属性
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前属性“${row.componentNo}”吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const eqpIdListsPuls = [];
      eqpIdListsPuls.push(row.id);
      await delByIds({
        ids: eqpIdListsPuls
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
const closeDialog = () => {
  TreedialogVisible.value = false;
  TabledialogVisible.value = false;
  // rightData.value.componentNo = "";
};
const addTableSensorType = () => {
  TableSensorType.value = "add";
  TabledialogSensorVisible.value = true;
};
const closeSensorDialog = () => {
  TableSensorType.value = "";
  TabledialogSensorVisible.value = false;
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}

.buttonGroup {
  display: flex;
  margin-right: 8px;
}

.status {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  max-width: 58px;
  height: 22px;
  font-size: 12px;
  line-height: 22px;
  color: #10b981;
  text-align: center;
  background: #b7ead9;
  border: 1px solid #b7ead9;
  border-radius: 4px;

  img {
    width: 16px;
    height: 16px;
  }
}

::v-deep .px-dropdown-menu {
  margin-bottom: 10px;
}

// ::v-deep .equip-wrap-common .equip-table-wrap[data-v-93c1cb48] {
//   width: calc(80% - 316px);
// }
::v-deep .equip-wrap-common .equip-tree-wrap {
  flex-shrink: 0;
}
</style>
